﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：MallWebApplicationServiceBase.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System.Threading.Tasks;
using TongTongMall.Application.Services;
using TongTongMall.Events;
using TongTongMall.MallWeb.Application.Configuration;
using TongTongMall.MallWeb.Application.Configuration.Session;
using TongTongMall.MallWeb.Application.Users;
using TongTongMall.MallWeb.Core.Identitys;
using TongTongMall.MallWeb.Core.Tenant.Services;
using TongTongMall.Oauth2._0.Models;
using TongTongMall.Redis.Cache.Configuration;

namespace TongTongMall.MallWeb.Application
{
    public abstract class MallWebApplicationServiceBase : ApplicationService
    {
        /// <summary>
        /// 全局配置项
        /// </summary>
        public IApplicationInstance Instance { get; set; } = ApplicationDefaultInstance.Instance;

        /// <summary>
        /// 重写父类Session，扩展Session内容
        /// </summary>
        public new IMallWebSession Session { get; set; } = NullMallWebSession.Instance;

        /// <summary>
        /// 事件总线
        /// </summary>
        public IEventBus EventBus { get; set; } = NullEventBus.Instance;

        /// <summary>
        /// 用户在redis内的管理
        /// </summary>
        public UserRedisManager UserRedisManager { get; set; }

        /// <summary>
        /// 租户在redis内的管理
        /// </summary>
        public TenantRedisManager TenantRedisManager { get; set; }

        /// <summary>
        /// redis的配置内容
        /// </summary>
        public IRedisConfiguration RedisConfigurationManager { get; set; } = RedisConfiguration.Default;


        /// <summary>
        /// 获取登录用户在redis内的信息
        /// </summary>
        /// <returns></returns>
        protected async Task<OAuthRedisUser> GetCurrentUser()
        {
            var userCacheKey = RedisKeys.Instance.UserAuthorizationAfterRedisKey(Session.TenantName, Session.UserID.ToString(), Session.Platform);
            var user = await UserRedisManager.GetUserInfo<OAuthRedisUser>(userCacheKey);
            return user;
        }

        /// <summary>
        /// 用户是否已经登录
        /// </summary>
        protected bool UserIsLogin { get { return Session.UserID.HasValue; } }

        /// <summary>
        /// 组合redis的value
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        protected string GroupRedisKey(params string[] values)
        {
            return RedisConfigurationManager.GroupKeys(values);
        }
    }
}
